import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
# print(sys.path)

import io
from mcp.types import ImageContent
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.utilities.types import Image
from PIL import ImageSequence

import forecast_tools.forecast as forecast_tools_forecast

dataset_path = "./dataset/"
dataset_file = "forecast_results.nc"

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')

mcp = FastMCP("weather_forecast_generation")

@mcp.tool()
async def generate_animations(
        num_days: int, 
        lat_lon: tuple[int, int], 
        timezone_delta: float, 
        interval: int
) -> list[ImageContent | None]:
    """使用气象数据集文件生成天气预报动画
    
    Args:
        num_days: 预报的天数。
        lat_lon: 元组的两个元素分别为用户指定地点的纬度（北纬为正，南纬为负）和经度（东经为正，西经为负）。若值为小数，需要四舍五入取整。
        timezone_delta: 用户指定地点的当地时间与世界标准时间的时差，单位为小时，允许数值为小数。例如，东八区为+8，西五区为-5。
        interval: 动画的帧间间隔，单位为ms。
    
    Returns:
        包含生成动画的ImageContent对象列表。如果动画生成失败，则返回None列表。
    """
    images = forecast_tools_forecast.generate_animations(os.path.join(dataset_path, dataset_file), num_days, 
                                                         lat_lon, timezone_delta, 
                                                         interval)
    
    img_list = []
    for image in images:
        img = None
        if image is not None:
            frames = [frame.copy() for frame in ImageSequence.Iterator(image)]
            buf = io.BytesIO()
            frames[0].save(
                buf,
                format='GIF',
                save_all=True,
                append_images=frames[1:],
                duration=interval,
                loop=0
            )
            img = Image(data=buf.getvalue(), format='GIF').to_image_content()
        img_list.append(img)
    
    return img_list

if __name__ == "__main__":
    mcp.run(transport='stdio')

# end of file
